import jdk.nashorn.internal.runtime.UnwarrantedOptimismException;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 08 - 25
 * Time: 21:08
 */
//牛客 数组中的逆序对
public class Solution5 {
    //法一 根据官方思路自己写的代码，递归有返回值
    public int InversePairs(int [] array) {
        return InversePairs(array, 0, array.length - 1);
    }
    public int InversePairs(int[] array, int left, int right) {
        int count2 = 0;
        int count3 = 0;
        if(left >= right) return 0;
        int mid = (left + right) / 2;
        count2 = InversePairs(array, left, mid);
        count3 = InversePairs(array, mid + 1, right);
        return merge(array, left, right, mid, count2 + count3);
    }
    public int merge(int[] array, int left, int right, int mid, int count1) {
        int[] tempArr = new int[right - left + 1];
        int s1 = left;
        int s2 = mid + 1;
        int k = 0;
        while(s1 <= mid && s2 <= right) {
            if(array[s2] < array[s1]) {
                count1 += mid + 1 - s1;
                count1 %= 1000000007;
                tempArr[k++] = array[s2++];
            }else {
                tempArr[k++] = array[s1++];
            }
        }
        while (s1 <= mid) {
            tempArr[k++] = array[s1++];
        }
        while (s2 <= right) {
            tempArr[k++] = array[s2++];
        }
        for (int i = 0; i < tempArr.length; i++) {
            array[i + left] = tempArr[i];
        }
        return count1;
    }
}

class Test {
    //法二 根据官方思路自己写的代码，递归没有返回值
    int count = 0;
    public int InversePairs(int [] array) {
        InversePairs(array, 0, array.length - 1);
        return count;
    }
    public void InversePairs(int[] array, int left, int right) {
        if(left >= right) return;
        int mid = (left + right) / 2;
        InversePairs(array, left, mid);
        InversePairs(array, mid + 1, right);
        merge(array, left, right, mid);
    }
    public void merge(int[] array, int left, int right, int mid) {
        int[] tempArr = new int[right - left + 1];
        int s1 = left;
        int s2 = mid + 1;
        int k = 0;
        while(s1 <= mid && s2 <= right) {
            if(array[s2] < array[s1]) {
                count += mid + 1 - s1;
                count %= 1000000007;
                tempArr[k++] = array[s2++];
            }else {
                tempArr[k++] = array[s1++];
            }
        }
        while (s1 <= mid) {
            tempArr[k++] = array[s1++];
        }
        while (s2 <= right) {
            tempArr[k++] = array[s2++];
        }
        for (int i = 0; i < tempArr.length; i++) {
            array[i + left] = tempArr[i];
        }
    }
}
